import json
import select
import socket
import sys
import time
from common_client import *


ssock = None
def listen():
	global ssock
	ssock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	#ssock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
	ssock.connect((HOST, PORT))
	all_socks = [ssock, sys.stdin]
	print(all_socks)
	while True:
		readable, writable, exceptional = select.select(all_socks, [], all_socks)
		if len(exceptional) >= 1:
			print('exceptional! %s' % (exceptional,))
			continue
		if len(readable) >= 1:
			s = readable[0]
			if s == sys.stdin: # keyboard
				bmsg = s.readline()
				if len(bmsg) <= 0:
					print('read 0; hangup')
					exit(3)
				msg = bmsg.strip()
				parse(msg)
			elif s == ssock: # server
				bmsg = s.recv(1024)
				if len(bmsg) <= 0:
					print('read 0; hangup')
					exit(3)
				msg = str(bmsg, 'utf-8').strip()
				jmsg = json.loads(msg)
				parse_server_message(jmsg)
			else:
				print('unknown socket:', s)
				exit(2)



def quit_game():
	return build_action('quit')

def parse(line):
	print('parse')
	line = line.strip()

	if len(line) < 1:
		return

	cmd = line[0]
	arg = line[1:].strip()
	print(cmd, arg)

	if cmd == 'g':
		msg = give_card(int(arg))
	elif cmd == 's':
		msg = start_game()
	elif cmd == 'c':
		msg = choose_row(int(arg))
	elif cmd == 'n':
		msg = set_name(arg)
	elif cmd == 'q':
		msg = quit_game()
	else:
		print('unknown cmd:', cmd)
		return
	send_msg(ssock,msg)

if __name__ == '__main__':
	try:
		while True:
			listen()
	except KeyboardInterrupt:
		print('interrupt - exiting')
		#TODO: close
		exit(9)
